import React from 'react'
import { Breadcrumb ,Form,Input,Select, Button ,Upload, message } from 'antd';
import { HomeOutlined, UserOutlined,LoadingOutlined, PlusOutlined,DeleteOutlined } from '@ant-design/icons'
import { useState,useEffect } from 'react';
import { useAppSelector,useAppDispatch } from '@/hooks';
import TitleCateSelect from '@/components/common/TitleCateSelect';
import { addTitle } from '@/store/reducers/article';
import { useHistory, useParams } from 'react-router-dom'
export default ()=> {
  // 获取当前路
  const dispatch=useAppDispatch()
  const history = useHistory()
  const [loading,setLoading]=useState(false)
  const [imageUrl,setImageUrl] = useState('')
  const token=useAppSelector(({test})=>test.token)
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 12 },
  };
  const validateMessages = {
    required: '${label} is required!',
    types: {
      email: '${label} is not a valid email!',
      number: '${label} is not a valid number!',
    },
    number: {
      range: '${label} must be between ${min} and ${max}',
    },
  };
  const onFinish = (values: any) => {
    console.log(values);
    values={...values.title,image:imageUrl}
    console.log(values);
    //疑问，怎么判断成功-------可以调用其then方法
    dispatch(addTitle(values)).then(()=>{
      console.log('文章添加成功')
      message.success(('添加成功'), 1).then(()=>{
        history.replace('/SelectTitle')
      })
    }) 
     
  };
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  const handleChange = info => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl =>{
        setLoading(true);
        setImageUrl(imageUrl)
        console.log(info.file.status.response,'00000000')
        // 返回图片名称info.file.response.data.img
        // 如果是组件，则要将info.file.response.data.img传给父组件的onChange方法
        console.log(info.file.response.data.img,'222222')
      }
      );
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  
  return(
    <div className='yx-user-maanager'>
      <Breadcrumb>
        <Breadcrumb.Item href="">
          <HomeOutlined />
        </Breadcrumb.Item>
        <Breadcrumb.Item href="">
          <UserOutlined />
          <span>新增文章</span>
        </Breadcrumb.Item>
        <Breadcrumb.Item></Breadcrumb.Item>
      </Breadcrumb>
      <Form {...layout} name="nest-messages" onFinish={onFinish} validateMessages={validateMessages}>
        <Form.Item name={['title', 'name']} label="文章名" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name={['title', 'author']} label="作者名" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name={['title', 'digest']} label="文章摘要" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name={['title', 'type']} label="文章类别">
          <TitleCateSelect value='全部' onChange={e=>console.log(e,'选择的东西')}/>
        </Form.Item>
        <Form.Item name={['title', 'image']} label="图片上传">
        <Upload
          listType="picture-card"
          className="avatar-uploader"
          // 为什么我加了这个，会有两张图片显示出来？
          // showUploadList={{showRemoveIcon:false,removeIcon:<DeleteOutlined />}}
          showUploadList={false}
          maxCount = {1}
          action="http://localhost:9000/api/v3/upload/img"
          headers={{
            Authorization :token || ''
          }}
          beforeUpload={beforeUpload}
          onChange={handleChange}
        >
          {imageUrl ? <img src={imageUrl} alt="文章封面" style={{ width: '100%', height:'100%'}} /> : uploadButton}
        </Upload>
        </Form.Item>
        <Form.Item name={['title', 'content']} label="文章内容">
          <Input.TextArea />
        </Form.Item>
        <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 8 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  )

}

